﻿function SpGridView() {

  var _dataCallbackType = 3;
  var _customCallbackType = 2;
  var _pageIndexChangeCallbackType = 1;
  var _expendedCallbackType = 4;
  var _saveEditCallbackType = 5;
  var _deleteCallbackType = 6;
  var _getEditValue = 7;
  this.CallbackTypes = { Data: _dataCallbackType, Custom: _customCallbackType, PageIndexChanged: _pageIndexChangeCallbackType, SaveEdit: _saveEditCallbackType, Delete: _deleteCallbackType, GetEditValue: _getEditValue };
  var _id;
  var _rowSelectedClass = "spgvRowActive";
  var _rowClass = "spgvRow";
  var _rowEditClass = "spgvRowEdit";
  var _rowEditSelectedClass = "spgvRowEditActive";
  var _rowExpendedClass = "spgvRowExpend";
  var _fistCellClass = "spgvFirstCell";
  var _cellClass = "spgvCell";
  var _serverEditMode;
  var _enable;
  var _enableMultySelectRow;
  var _currentPageIndexId;
  var _currentPageSizeId;
  var _sortColumnIndex;
  var _sortType;
  var _parrentKey;
  var _clientRequestId;
  var _instance = this;
  var _collapseImagePath;
  var _expendedImagePath;
  var _hashParameter = Library.WebControl.Hashtable.CreateHashtable();
  var _util = Library.WebControl.Util;
  var _isEdittingState = false;
  var _controlsEdit = null;
  var _columns;
  var _hasExpendColumn = false;
  var _confirmDeleteMessage = "";
  var _showLoadingPanel = false;
  var _enableFilter = false;
  var _rowClicking = null;
  var _rowClicked = null;
  var _beforeCallback = null;
  var _selectedRowChanged = null;
  var _newEditInitControl = null;
  var _callbackComplete = null;
  var _handleRowDoubleClick = null;
  var _preventUnSelectByClick;
  this.Init = function(clientName, id, enable, enableMultySelectRow, currentPageIndexId, currentPageSizeId, sortColumnIndex, sortType, parrentKey, clientRequestId, showLoadingPanel, filter, editMode, preventUnSelectByClick) {
    _globalHashObject.Add(clientName, _instance);
    window[clientName] = _instance;
    _id = id;
    _enable = enable;
    _enableMultySelectRow = enableMultySelectRow;
    _currentPageIndexId = currentPageIndexId;
    _currentPageSizeId = currentPageSizeId;
    _sortColumnIndex = sortColumnIndex;
    _sortType = sortType;
    _parrentKey = parrentKey;
    _clientRequestId = clientRequestId;
    _showLoadingPanel = showLoadingPanel == 1;
    _enableFilter = filter;
    _serverEditMode = editMode;
    _preventUnSelectByClick = preventUnSelectByClick;
  };
  this.InitColumns = function(columns) {
    _columns = columns;
  };
  this.ConfirmDeleteText = function() {
    if (arguments.length > 0) _confirmDeleteMessage = arguments[0];
    return _confirmDeleteMessage;
  };

  this.InitExpendImage = function(collapseImagePath, expendedImagePath) {
    _collapseImagePath = collapseImagePath;
    _expendedImagePath = expendedImagePath;
  };

  function getObjectById(id) {
    return _util.GetObjectById(id);
  };
  function findFilterRow() {
    var table = getTableGridView();
    if (table == null) return null;
    var b = _util.FindFirstChild(table, "tbody");
    if (b == null) b = table;
    return _util.FindFirstChild(b, "tr", "spfilterrow");
  };
  this.GetFilterControl = function() {
    var fr = findFilterRow();
    if (fr != null) {
      var input = fr.getElementsByTagName("input");
      if (arguments.length > 0)
        return input[arguments[0]];
      return input;
    }

    return null;
  };
  function getTableGridView() {
    var div = _util.FindFirstChild(_id, "div");
    return _util.FindFirstChild(div, "table");
  };
  this.IsSelected = function(row) {
    return isSelectedRow(row);
  };
  function isSelectedRow(row) {
    var clzz = _util.GetClass(row);
    return clzz == _rowSelectedClass || clzz == _rowEditSelectedClass;
  };
  function isNormalRow(row) {
    var clzz = _util.GetClass(row);
    return clzz == _rowClass;
  };
  function isEditRow(row) {
    var clzz = _util.GetClass(row);
    return clzz == _rowEditClass || clzz == _rowEditSelectedClass;
  };
  this.IsEdited = function(r) {
    return isEditRow(r);
  };
  function getKeyFromRow(row) {
    return row.getAttribute("__spgvitemkey_");
  };
  function getValueFromCell(cell) {
    return cell.getAttribute("__spgvitemprovalue_");
  };
  function setValueToCell(cell, value) {
    cell.setAttribute("__spgvitemprovalue_", value);
  };
  this.GetKeyFromRow = function(row) {
    return getKeyFromRow(row);
  };
  function selectRow(row) {
    if (!isEditRow(row))
      _util.SetClass(row, _rowSelectedClass);
    else
      _util.SetClass(row, _rowEditSelectedClass);
  };
  function unSelectRow(row) {
    if (!isEditRow(row))
      _util.SetClass(row, _rowClass);
    else
      _util.SetClass(row, _rowEditClass);
  };

  function commonCallback(callbackType, callbackParameter, callbackFunction, callbackObject) {
    if (_beforeCallback != null)
      _beforeCallback(_instance, {
        CallbackType: callbackType,
        Parameter: callbackParameter
      });
    var ajaxRequest = Library.WebControl.Ajax.CreateRequest();
    ajaxRequest.SetData("__SPGRIDVIEWPK_=" + _parrentKey + "&__SPGRIDVIEWSID_=" + _clientRequestId + "&__SPGRIDVIEWRQF_=" + callbackType + "&__SPGRIDVIEWRQP_=" + encodeURIComponent(callbackParameter) + "&" + _hashParameter.ToQuery());
    _hashParameter.Clear();
    ajaxRequest.SendCallback({
      T: callbackType,
      P: callbackParameter,
      F: callbackFunction,
      O: callbackObject
    }, callbackComplete);
    if (_showLoadingPanel)
      _util.ShowLoadingPanel({
        Parrent: _id,
        LoadingId: _id + "_LDP"
      });
  };
  function callbackComplete(sender, args) {
    if (_showLoadingPanel)
      _util.HideLoadingPanel(_id + "_LDP");
    var responseArgs = _util.ParseAjaxResponse(args.ResponseText);
    responseArgs.Parameter = sender.P;
    responseArgs.CallbackType = sender.T;
    if (!responseArgs.IsValid) {
      alert(responseArgs.Result);
    }
    else {
      switch (sender.T) {
        case _dataCallbackType:
          break;
        case _saveEditCallbackType:
        case _customCallbackType:
        case _pageIndexChangeCallbackType:
        case _deleteCallbackType:
          _instance.CancelEdit();
          var mainGrid = _util.GetObjectById(_id);
          var editSource = removeDivEditSource(mainGrid);
          _util.EvalScriptAndHtml(responseArgs.Data, mainGrid);
          if (editSource != null) {
            mainGrid.appendChild(editSource);
          }
          setTimeout(function() { _instance.SetFocus(); }, 100);

          break;
        case _expendedCallbackType:
          var rowIndex = -1;
          var row = sender.O.Row;
          var rows = row.parentNode.rows;
          for (var i = 0; i < rows.length; i++) {
            if (row == rows[i]) {
              rowIndex = i + 1;
              break;
            }
          }
          var expendRow = row.parentNode.insertRow(rowIndex);
          while (expendRow.cells.length > 0) {
            expendRow.deleteCell(0);
          }
          _util.SetClass(expendRow, _rowExpendedClass);
          var firstCell = expendRow.insertCell(0);
          _util.SetClass(firstCell, _fistCellClass);
          var secondCell = expendRow.insertCell(1);
          secondCell.colSpan = row.cells.length - 1;
          _util.SetClass(secondCell, _cellClass);
          _util.EvalScriptAndHtml(responseArgs.Data, secondCell);
          break;

      }
    }
    if (typeof (sender.F) == "function")
      sender.F(_instance, responseArgs);
    if (_callbackComplete != null) {
      _callbackComplete(_instance, responseArgs);
    }
  };

  function curPageIndex() {
    return findPagingTextBox("current-page-index");
  };
  function curPageSize() {
    return findPagingTextBox("current-page-size");
  };
  function findPagingTextBox(clzz) {
    var ips = pagingTextBox();
    if (ips != null) {
      for (var i = 0; i < ips.length; i++) {
        var ip = ips[i];
        var type = ip.type;
        if (!type) type = ip.getAttribute("type");
        if (type) type = type.toLowerCase();
        if (type == "text") {
          var czz = _util.GetClass(ip);  //type.className;
          //if (!czz) czz = ip.getAttribute("class");
          if (czz == clzz) return ip;
        }
      }
    }
    return null;
  };
  function pagingTextBox() {
    var grid = _util.GetObjectById(_id);
    var spgvDivPaging = _util.FindFirstChild(grid, "div", "spgvDivPaging");
    if (spgvDivPaging != null) {
      return spgvDivPaging.getElementsByTagName("input");
    }
    return null;
  };

  function fillPageIndexInfomation() {
    var pIndex = "1";
    var pIndexCtr = curPageIndex();
    if (pIndexCtr != null) pIndex = pIndexCtr.value
    _hashParameter.Add("__SPGRIDVIEWCPID_", pIndex);
    var pSize = "-1";
    var pSizeCtr = curPageSize();
    if (pSizeCtr != null) pSize = pSizeCtr.value;
    _hashParameter.Add("__SPGRIDVIEWCPS_", pSize);
    _hashParameter.Add("__SPGRIDVIEWSCI_", _sortColumnIndex);
    _hashParameter.Add("__SPGRIDVIEWST_", _sortType);
    if (_enableFilter) {
      var ft = Array();
      var fr = findFilterRow();
      if (fr != null) {
        for (var i = 0; i < fr.cells.length; i++) {
          var c = fr.cells[i];
          var input = c.getElementsByTagName("input");
          if (input && input.length > 0) {
            ft.push(i);
            ft.push(input[0].value);
          }
        }
      }
      _hashParameter.Add("__SPGRIDVIEWFD_", _util.ToArrayString(ft));
    }
  };
  this.GetParrentKey = function() {
    return _parrentKey;
  };
  this.SendCallback = function(parameter, callbackFunction) {
    fillPageIndexInfomation();
    commonCallback(_customCallbackType, parameter, callbackFunction, {});
  };
  this.SendDataCallback = function(parameter, callbackFunction) {
    commonCallback(_dataCallbackType, parameter, callbackFunction, {});
  };
  this.Refresh = function() {
    if (!_enable)
      return;
    fillPageIndexInfomation();
    commonCallback(_pageIndexChangeCallbackType, "", function(s, e) {
    }, {});
  };
  this.Sort = function(columnIndex, sortType) {
    _sortColumnIndex = columnIndex;
    _sortType = sortType;
    _instance.Refresh();
  };
  this.GetPage = function(pageIndex) {
    var pIndexCtr = curPageIndex();
    if (pIndexCtr != null) pIndexCtr.value = pageIndex;
    _instance.Refresh();
  };
  this.Expended = function(img) {
    if (!_enable)
      return;
    var cell = img.parentNode;
    var row = cell.parentNode;
    var expendedKey = getKeyFromRow(row);
    if (expendedKey == null || expendedKey == "")
      return;

    img.onclick = function() {
      _instance.Collapse(img);
    };
    img.src = _expendedImagePath;
    _hashParameter.Add("__SPGRIDVIEWEXK_", expendedKey);
    var rows = row.parentNode.childNodes;
    commonCallback(_expendedCallbackType, "", function(s, e) {
    }, {
      Row: row
    });
  };
  this.Collapse = function(img) {
    if (!_enable)
      return;
    var row = img.parentNode.parentNode;
    var nextRow = row.nextElementSibling ? row.nextElementSibling : row.nextSibling;
    if (nextRow) {
      if (_util.GetClass(nextRow) == _rowExpendedClass) {
        nextRow.parentNode.removeChild(nextRow);
      }
    }
    img.src = _collapseImagePath;
    img.onclick = function() {
      _instance.Expended(img);
    }
  };
  this.Visible = function() {
    var grid = getObjectById(_id);
    if (arguments.length > 0) {
      var d = arguments[0] ? "" : "none";
      grid.style.display = d;
    }
    return grid.style.display != "none";
  };
  this.Enable = function() {
    if (arguments.length > 0) _enable = arguments[0];
    return _enable;
  };

  this.SetFocus = function() {
    try {
      _util.GetObjectById(_id).FindFirstChild("div").FindFirstChild("div").FindFirstChild("input").focus();
    } catch (e) {
      return false;
    }
    return true;
  };

  this.GetSelectedRows = function() {
    var selectedRows = new Array();
    var table = getTableGridView();
    if (table != null) {
      for (var i = 0; i < table.rows.length; i++) {
        if (isSelectedRow(table.rows[i])) {
          selectedRows.push(table.rows[i]);
          if (!_enableMultySelectRow) return selectedRows;
        }
      }
    }

    return selectedRows;
  };
  this.GetSelectedRow = function() {
    var rows = _instance.GetSelectedRows();
    if (rows.length > 0)
      return rows[0];
    return null;
  };
  this.GetSelectedKey = function() {
    var keys = _instance.GetSelectedKeys();
    if (keys.length > 0)
      return keys[0];
    return null;
  };
  this.GetVisibleRows = function() {
    var rows = new Array();
    var table = getTableGridView();
    if (table != null) {
      for (var i = 0; i < table.rows.length; i++) {
        if (isSelectedRow(table.rows[i]) || isNormalRow(table.rows[i])) {
          rows.push(table.rows[i]);
        }
      }
    }

    return rows;
  };
  this.GetRowByKey = function(key) {
    var rows = _instance.GetVisibleRows();
    for (var i = 0; i < rows.length; i++) {
      if (_instance.GetKeyFromRow(rows[i]) == key) return rows[i];
    }
    return null;
  };
  this.GetSelectedKeys = function() {
    var keys = new Array();
    var selectedRows = _instance.GetSelectedRows();
    for (var i = 0; i < selectedRows.length; i++) {
      var key = getKeyFromRow(selectedRows[i]);
      keys.push(key);
    }
    return keys;
  };
  this.GetEdittedRow = function() {
    var table = getTableGridView();
    if (table != null) {
      for (var i = 0; i < table.rows.length; i++) {
        if (isEditRow(table.rows[i])) {
          return table.rows[i];
        }
      }
    }
    return null;
  };

  this.UnSelectAll = function() {
    var selectedRows = _instance.GetSelectedRows();
    for (var i = 0; i < selectedRows.length; i++) {
      unSelectRow(selectedRows[i]);
    }
  };
  function handleRowClick(row) {
    if (isEditRow(row)) {
      if (!isSelectedRow(row)) {
        if (!_enableMultySelectRow) {
          _instance.UnSelectAll();
        }
        selectRow(row);
        if (!_enableMultySelectRow) {
          if (_selectedRowChanged != null)
            _selectedRowChanged(_instance, {});
        }
      }
      return;
    }
    var e = { Cancel: false, Row: row };
    if (_rowClicking != null)
      _rowClicking(_instance, e);
    if (e.Cancel) return;
    if (!_enable)
      return;
    if (isSelectedRow(row)) {
      if (!_preventUnSelectByClick)
        unSelectRow(row);
    }
    else {
      if (!_enableMultySelectRow) {
        _instance.UnSelectAll();
      }
      selectRow(row);
      if (!_enableMultySelectRow) {
        if (_selectedRowChanged != null)
          _selectedRowChanged(_instance, {});
      }
    }
    if (_rowClicked != null)
      _rowClicked(_instance, { Row: row });
  };
  this.HandleRowClick = handleRowClick;
  this.AddParameter = function(key, value) {
    _hashParameter.Add(key, value);
  };

  function getDivEditSource(grid) {
    return _util.FindLastChild(grid, "span");
  };
  function removeDivEditSource(grid) {
    if (!grid)
      grid = _util.GetObjectById(_id);
    var edit = getDivEditSource(grid);
    if (edit != null) {
      grid.removeChild(edit);
    }

    return edit;
  };
  /*
  get edit control in edit mode
  */
  this.GetEdittedControl = function(columnIndex) {
    if (_instance.GetEdittedRow() == null) return null;
    if (!_columns || !_columns.length) return null;
    if (_hasExpendColumn) columnIndex++;
    if (columnIndex >= 0 && columnIndex < _columns.length)
      return _columns[columnIndex].Ctr;
    return null;
  };
  this.SaveEdit = function(parameter, callbackFunction) {
    if (_instance.GetEdittedRow() == null) return;
    var parms = new Array();
    if (_columns && _columns.length) {
      var i = _hasExpendColumn ? 1 : 0;
      for (; i < _columns.length; i++) {
        var editValue = null;
        var ctrEdit = _columns[i];
        if (ctrEdit.Ctr) {
          switch (ctrEdit.Type) {
            case 1: //text            
              editValue = ctrEdit.Ctr.GetValue();
              break;
            case 3: // combo       
            case 5:   // ex combo
              editValue = ctrEdit.Ctr.GetValue();
              if (editValue == null || editValue == "") editValue = ctrEdit.Ctr.GetText();
              break;
            case 2: //date  
              editValue = ctrEdit.Ctr.ToString("yyyyMMdd");
              break;
            case 4: //spint
              editValue = ctrEdit.Ctr.GetValue();
              if (editValue == NaN) {
                editValue = "";
              }
            default:
              break;
          }

          if (editValue == null)
            editValue = "";
          parms.push(ctrEdit.Name);
          parms.push(editValue);
        }
        //para += ctrEdit.Name + ":" + editValue + ;
      }
    }
    var para = _util.ToArrayString(parms);
    _instance.AddParameter("__SPGRIDVIEWSEPR_", para);
    var editRow = _instance.GetEdittedRow();
    if (editRow != null) {
      var key = getKeyFromRow(editRow);
      if (key != null)
        _instance.AddParameter("__SPGRIDVIEWPRK_", key);
    }

    fillPageIndexInfomation();
    commonCallback(_saveEditCallbackType, parameter, callbackFunction, {});
  };

  this.DeleteSelectedRow = function(parameter, callbackFunction) {
    var keys = _instance.GetSelectedKeys();
    var paras = _util.ToArrayString(keys);

    _instance.AddParameter("__SPGRIDVIEWPRK_", paras);
    fillPageIndexInfomation();
    commonCallback(_deleteCallbackType, parameter, callbackFunction, {});
  };
  this.CancelEdit = function() {
    var divSource = getDivEditSource(_id);
    if (divSource == null)
      return;
    var row = _instance.GetEdittedRow();
    if (row == null)
      return;
    var j = _hasExpendColumn ? 1 : 0;
    for (; j < row.cells.length; j++) {
      var controlEdit = _columns[j];
      var divControl = divSource.childNodes[j];
      var cell = row.cells[j];
      if (controlEdit.Ctr) {
        while (cell.firstChild) {
          divControl.appendChild(cell.firstChild);
        }
        switch (controlEdit.Type) {
          case 1: //text                                
            break;
          case 2: //date
            //setValueToCell(cell, controlEdit.Ctr.ToString("yyyy|MM|dd"));
            //break;
          case 3: //combo
            //setValueToCell(cell, controlEdit.Ctr.GetValue());
            //break;
          case 5: 	// ex combo
          case 4: //spin
            //setValueToCell(cell, controlEdit.Ctr.GetValue());
            setValueToCell(cell, cell.LibEditValue);
          default:
            break;
        }
        cell.innerHTML = cell.LibEditText; //controlEdit.Ctr.GetText();
      }
    }
    if (row.isNewRow) {
      row.parentNode.removeChild(row);
    }
    else {
      _util.SetClass(row, _rowClass);
    }
  };
  this.NewEdit = function() {
    _instance.CancelEdit();
    if (_columns == null)
      return;
    var divSource = getDivEditSource(_id);
    if (divSource == null)
      return;
    var table = getTableGridView();
    if (table != null) {
      var firstRowIndex = 1;
      if (_enableFilter) firstRowIndex++;
      var row = table.insertRow(firstRowIndex);
      row.isNewRow = true;
      //row.setAttribute("onclick", clie ".HandleRowClick(this);");
      row.onclick = function() { _instance.HandleRowClick(row); };
      _util.SetClass(row, _rowEditSelectedClass);
      for (var i = 0; i < _columns.length; i++) {

        var cell = row.insertCell(i);
        cell.LibEditValue = null;
        cell.LibEditText = "";
        _util.SetClass(cell, i == 0 ? _fistCellClass : _cellClass);

        var controlEdit = _columns[i];
        if (controlEdit.Ctr) {
          controlEdit.Ctr.SetValue(null);
          controlEdit.Ctr.Enable((controlEdit.State & 1) == 1);
          if (_newEditInitControl != null) {
            _newEditInitControl(_instance, { Control: controlEdit });
          }
        }

        var child = divSource.childNodes[i];
        while (cell.firstChild) {
          cell.removeChild(cell.firstChild);
        }
        while (child.firstChild) {
          cell.appendChild(child.firstChild);
        }
      }
    }
  };
  function getEditValues(e, row, divSource) {
    var values = null;
    if (e != null && e.IsValid) {
      values = _util.ParseArrResponse(e.Result);
    }
    var i = _hasExpendColumn ? 1 : 0;
    for (; i < row.cells.length; i++) {
      var cell = row.cells[i];
      var controlEdit = _columns[i];
      var value = null;
      var text = null;
      var callSetText = false;
      if (values == null) {
        switch (controlEdit.Edit) {
          case 1: // html
            value = _util.Trim(cell.innerHTML);
            text = value;
            break;
          case 2: // attr
            value = getValueFromCell(cell);
            text = _util.Trim(cell.innerHTML);
            break;
          case 3: // server
            break
        }
      } else {
        var j = i;
        if (_hasExpendColumn) j--;
        j = j * 3;
        value = values[j];
        text = values[j + 1];
        callSetText = values[j + 2] == "1";
      }
      switch (controlEdit.Type) {
        case 1: //text edit          
          break;
        case 2: //date edit                        
          if (value == null || value == "") {
            value = null;
          }
          else {
            var ps = value.split('|');
            value = new Date(ps[0], ps[1], ps[2], 0, 0, 0);
          }
          break;
        case 3: //combo edit
          break;
        case 4: //spin
          if (value == "") value = 0;
          else value = parseFloat(value);
          break;
        case 5: // ex cbx
          if (values == null) callSetText = true;
          break;
        default:
          continue;
      }
      if (controlEdit.Ctr) {
        controlEdit.Ctr.SetValue(value);
        if (callSetText) controlEdit.Ctr.SetText(text);
        controlEdit.Ctr.Enable((controlEdit.State & 2) == 2);
      }

      var child = divSource.childNodes[i];
      while (cell.firstChild) {
        cell.removeChild(cell.firstChild);
      }
      while (child.firstChild) {
        cell.appendChild(child.firstChild);
      }
      cell.LibEditValue = value;
      cell.LibEditText = text;
    }
  };
  this.InlineEdit = function() {
    if (_columns == null)
      return;
    var divSource = getDivEditSource(_id);
    if (divSource == null)
      return;
    var row = _instance.GetSelectedRow();
    if (row != null) {
      _instance.CancelEdit();
      _util.SetClass(row, _rowEditSelectedClass);
      if (_serverEditMode == 1)
        commonCallback(_getEditValue, _instance.GetKeyFromRow(row), setTimeout(function(s, e) { getEditValues(e, row, divSource); }, 200), {});
      else {
        getEditValues(null, row, divSource);
      }

    }
  };

  this.AddHandler = function(t, f) {
    switch (t) {
      case 1: //BeforeCallback
        _beforeCallback = f;
        break;
      case 2: //SelectedRowChanged
        _selectedRowChanged = f;
        break;
      case 3: //RowClicking
        _rowClicking = f;
        break;
      case 4: //RowClicked
        _rowClicked = f;
        break;
      case 5: // init new control
        _newEditInitControl = f;
        break;
      case 6:
        _callbackComplete = f;
        break;
      case 7: // handle row double click
        _handleRowDoubleClick = f;
        break;
    }
  };

  function moveFocusToOffset(offset) {
    if (_enableMultySelectRow) return;

    var selectedRow = _instance.GetSelectedRow();
    if (selectedRow == null) {
      //if (offset < 0) return;
      // focus first row
      var table = getTableGridView();
      if (table != null) {
        for (var i = 0; i < table.rows.length; i++) {
          if (isNormalRow(table.rows[i])) {
            selectRow(table.rows[i]);
            break;
          }
        }
      }
    } else {
      var row = null;
      if (offset < 0) {
        row = selectedRow.previousSibling;
        while (row != null && row.nodeType != 1) row = row.previousSibling;
      } else {
        row = selectedRow.nextSibling;
        while (row != null && row.nodeType != 1) row = row.nextSibling;
      }
      if (row != null && isNormalRow(row)) {
        unSelectRow(selectedRow);
        selectRow(row);
      }
    }
    _instance.SetFocus();

  };
  function keyDown(e) {
    if (!_enable) return;
    //var k = _util.GetKey(e);
    if (!_util.HandlePress(e, _util.Keys.ARROW_UP, function() { moveFocusToOffset(-1); })) {
      return false;
    }
    if (!_util.HandlePress(e, _util.Keys.ARROW_DOWN, function() { moveFocusToOffset(1); })) {
      return false;

    }
    return true;
    //switch(k) {
    //	case 38:// up arrow
    //		moveFocusToOffset(-1);
    //		break;
    //		case 40:// down arrow
    //			moveFocusToOffset(1);
    //			break;	
    //	}
  };

  this.Call = function(t, p) {
    if (!_enable) return;
    switch (t) {
      case 1: //KeyPress				
        return _util.HandleEnterPress(p, function() { _instance.Refresh(); });
      case 2: // filter
        return _util.HandleEnterPress(p, function() { _instance.GetPage(1); });
      case 3: //OnClickDeleteIcon				
        if (_confirmDeleteMessage != "") {
          if (!confirm(_confirmDeleteMessage)) {
            return;
          }
        }
        _instance.DeleteSelectedRow("", null);
        break;
      case 4: //OnClickSaveIcon
        _instance.SaveEdit("", null);
        break;
      case 5: // Handle row click
        handleRowClick(p);
        break;
      case 6: // Key down
        return keyDown(p);
        break;
      case 7: // handle double click
        if (_handleRowDoubleClick != null) {
          _handleRowDoubleClick(_instance, new Object());
        }
        break
    }
  };
};
